package com.gzhryc.shared_device.oem.code;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.Date;

import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntityBuilder;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import com.gzhryc.common.IDTools;
import com.gzhryc.common.data.dto.BaseResponse;
import com.gzhryc.common.json.JsonTools;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.common.secruity.EncryptTools;

public class ResourceAPIServer {

    static Logger log = Logger.getLogger(ResourceAPIServer.class);

    static ResourceAPIServer me;

    public static Integer placeThumbWidth = 300;
    public static Integer placeThumbHeight = 300;
    
    public static Integer deviceThumbWidth = 300;
    public static Integer deviceThumbHeight = 300;
    
    public static Integer memberFaceThumbWidth = 150;
    public static Integer memberFaceThumbHeight = 150;

    public static String placePath = "/place/images";
    public static String devicePath = "/device/images";
    public static String faultPath = "/fault/images";
    public static String agentPath = "/agent/images";
    public static String memberPath = "/member/images";
    public static String iconPath = "/judao/icon";

    public static ResourceAPIServer self(){
        if(me == null){
            me = new ResourceAPIServer();
        }
        return me;
    }

    private String resDomain;
    private String resToken;
    private String resId;

    CloseableHttpClient httpclient;

    public ResourceAPIServer() {
        this.httpclient = HttpClients.createDefault();
    }

    public void initial(String resDomain,String resToken,String resId){
        this.resDomain = resDomain;
        this.resToken = resToken;
        this.resId = resId;
    }

    /**
     * 上传图片
     * @param file
     * @return
     */
    public String uploadImg(String path,File file) {
        CloseableHttpResponse response = null;
        try {
            if (file != null) {
                FileBody bin = new FileBody(file);
                HttpEntity reqEntity = MultipartEntityBuilder.create().addPart("file", bin).build();

                String transferToken = buildTransferToken();

                //按月创建目录
                String dirPath = DateFormatUtils.format(new Date(),"yyyyMM");
                String url = resDomain + "/mng/api/upload.do";
                String authorization = transferToken + ":" + path + File.separator + dirPath;

                HttpPost httpPost = new HttpPost(url);
                httpPost.addHeader("authorization",authorization);
                httpPost.setEntity(reqEntity);

                log.info("上传图片，接口：{{0}}，权限：{{1}}",url,authorization);

                response = httpclient.execute(httpPost);
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    String str = EntityUtils.toString(entity, Charset.forName("UTF-8"));
                    if(JsonTools.isJsonStr(str)) {
                        log.info("上传图片响应：{{0}}",str);
                        UploadResult result = JsonTools.fromJson(str, UploadResult.class);
                        if (result != null && result.getCode() == 200) {
                            return result.getBody();
                        }
                    }else{
                        log.error("上传图片无响应，路径：" + path);
                    }
                }else{
                    log.error("上传图片无响应，路径：" + path);
                }
            }
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    log.error(e.getMessage(), e);
                }
            }
        }
        return null;
    }

    public String buildTransferToken(){
        String timestamp = IDTools.getTimestampID();        //毫秒级
        return EncryptTools.md5(timestamp  + resToken + resId) + timestamp + resId;
    }

    public static class UploadResult extends BaseResponse<String> {

		private static final long serialVersionUID = 1L;
		
	}
}
